using System.IO;
using log4net.Core;
using Quiki.ExpressionParsers;

namespace Quiki.Templates
{
    public class IncludeFileTemplate : IWikiTemplate
    {
        public IncludeFileTemplate(ILogger logger, DocumentProcessorSettings settings)
        {
            this.settings = settings;
            this.logger = logger;
        }

        public string TemplateName
        {
            get { return "include"; }
        }

        public void Expand(WikiTemplateElement element, WikiDocument document, DocumentGraph documentGraph)
        {
            // nothing to expand
        }

        public void Format(WikiTemplateElement element, HtmlFormatterContext context)
        {
            if (element.TemplateParameters.Count != 1)
            {
                logger.Log(Level.Warn, "'include' template does not have the include file specified");
                return;
            }

            string includeFileName = element.TemplateParameters[0];
            string fullIncludeFileName = Path.Combine(settings.InputDir, includeFileName);

            if (false == File.Exists(fullIncludeFileName))
            {
                logger.Log (Level.Warn, "'include' template file '{0}' does not exist", fullIncludeFileName);
                return;
            }

            string fileContents = File.ReadAllText(fullIncludeFileName);

            context.Writer.InnerWriter.Write (fileContents);                        
        }

        private readonly DocumentProcessorSettings settings;
        private readonly ILogger logger;
    }
}